package com.gudy.counter.service.impl;


import com.google.common.collect.Maps;
import com.gudy.counter.bean.*;
import com.gudy.counter.cache.OrderCacha;
import com.gudy.counter.cache.RedisStringCache;
import com.gudy.counter.cache.StockCache;
import com.gudy.counter.enumutil.CacheType;
import com.gudy.counter.service.AccountSerivce;
import com.gudy.counter.service.OrderSerivce;
import com.gudy.counter.thirdpaet.order.CmdType;
import com.gudy.counter.thirdpaet.order.OrderCmd;
import com.gudy.counter.thirdpaet.order.OrderDirection;
import com.gudy.counter.thirdpaet.order.OrderType;
import com.gudy.counter.util.ConstCommon;
import com.gudy.counter.util.DBUtil;
import com.gudy.counter.util.JsonUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderSerivce {

    @Autowired
    private AccountSerivce accountSerivce;

    @Override
    public CounterRes queryBalance(long uid) {
        long balance = DBUtil.queryBalance(uid);
        if (balance >= 0){
            return new CounterRes(ConstCommon.SUCCESS,"资金获取成功",balance);
        }
        return new CounterRes(ConstCommon.RELOGIN,"资金获取为空",0);
    }

    @Override
    public CounterRes queryPosiInfo(long uid) {
        List<PosiInfo> posiInfos = DBUtil.queryPosiInfo(uid);
        if (posiInfos != null && posiInfos.size() > 0){
            return new CounterRes(ConstCommon.SUCCESS,"持仓获取成功",posiInfos);
        }
        return new CounterRes(ConstCommon.RELOGIN,"获取持仓失败",posiInfos);
    }

    @Override
    public CounterRes queryOrderInfo(long uid) {
        List<OrderInfo> orderInfos = DBUtil.queryOrderInfo(uid);
        if (orderInfos !=null && orderInfos.size() > 0){
            return new CounterRes(ConstCommon.SUCCESS,"委托获取成功",orderInfos);
        }
        return new CounterRes(ConstCommon.RELOGIN,"委托获取失败",orderInfos);
    }

    @Override
    public CounterRes queryTradeInfo(long uid) {
        List<TradeInfo> tradeInfos = DBUtil.queryTradeInfo(uid);
        if (tradeInfos != null && tradeInfos.size() > 0){
            return new CounterRes(ConstCommon.SUCCESS,"成交获取成功",tradeInfos);
        }
        return new CounterRes(ConstCommon.RELOGIN,"成交获取失败",tradeInfos);
    }

    @Override
    public CounterRes OrderCmd(long uid,short type,long timestamp,int code,byte direction,long price,long volume,byte ordertyle,String token) {
        //获取登录人员的缓存信息，扣减账户余额
        String accountInfo = RedisStringCache.queryCache(token, CacheType.ACCOUNT);
        Account account = JsonUtil.fromJson(accountInfo, Account.class);
        long balance = account.getBalance();
        String password = account.getPassword();
        long totalprice = volume * price;
        if (totalprice >= balance){
            return new CounterRes(ConstCommon.FALA,"账户余额不足",null);
        }
        balance = balance - totalprice;
        int balanceStatus = DBUtil.updateBalance(balance,uid, password);
        if (balanceStatus <= 0){
            return new CounterRes(ConstCommon.FALA,"账户余额扣减失败",null);
        }
        account.setBalance(balance);
        RedisStringCache.saveCache(token,JsonUtil.toJson(account),CacheType.ACCOUNT);

        //删除库存信息
        OrderCmd orderCmd = OrderCmd.builder().type(CmdType.of(type)).uid(uid).timestamp(timestamp).code(code).direction(OrderDirection.of(direction)).price(price).volume(volume).orderType(OrderType.of(ordertyle)).build();
        //扣减redis库存成功,那么就扣减数据库库存
        CounterRes counterRes = RedisStringCache.reduceStock(String.valueOf(code), String.valueOf(volume));
        if (counterRes.getCode() == 0){
            int status = DBUtil.saveOrder(orderCmd);
            //插入缓存使用websocket通知前端连接对象推送对应的数据回到前端
            new OrderCacha().saveOrder(orderCmd,status);
            if (status > 0){
                String realStock = RedisStringCache.queryCache(String.valueOf(code), CacheType.AFFORDCOUR);
                Map<String,Object> resMap  = Maps.newHashMap();
                resMap.put("realStock",realStock);
                resMap.put("balance",balance);
                StockCache.setStocks(String.valueOf(code),Integer.valueOf(realStock));
                return new CounterRes(ConstCommon.SUCCESS,"添加成功:"+orderCmd,resMap);
            }
        }else{
            return new CounterRes(ConstCommon.FALA,counterRes.getMessage(),null);
        }
        return new CounterRes(ConstCommon.FALA,"添加失败:"+orderCmd,null);
    }

    @Override
    public CounterRes saleOrder(long uid, short type, long timestamp, int code, byte direction, long price, long volume, byte ordertyle, String token) {
        String accountInfo = RedisStringCache.queryCache(token, CacheType.ACCOUNT);
        Account account = JsonUtil.fromJson(accountInfo, Account.class);
        long balance = account.getBalance();
        String password = account.getPassword();
        long totalprice = volume * price;
        balance = balance + totalprice;
        int balanceStatus = DBUtil.updateBalance(balance,uid, password);
        OrderTotalInfo orderTotalInfo = DBUtil.queryOrderbyUidAndCode(uid, code);
        if (orderTotalInfo.getOcount() < volume){
            return new CounterRes(ConstCommon.FALA,"证券出售数量不足请检查",null);
        }
        if (balanceStatus <= 0){
            return new CounterRes(ConstCommon.FALA,"证券出售交易未成功",null);
        }
        account.setBalance(balance);
        RedisStringCache.saveCache(token,JsonUtil.toJson(account),CacheType.ACCOUNT);
        OrderCmd orderCmd = OrderCmd.builder().type(CmdType.of(type)).uid(uid).timestamp(timestamp).code(code).direction(OrderDirection.of(direction)).price(price).volume(volume).orderType(OrderType.of(ordertyle)).build();

        CounterRes counterRes = RedisStringCache.saveStock(String.valueOf(code), String.valueOf(volume));
        if (counterRes.getCode() == 0){
            CounterRes counterRess = DBUtil.saleOrder(orderCmd);
            //插入缓存使用websocket通知前端连接对象推送对应的数据回到前端
            new OrderCacha().saveSaleOrder(orderCmd,Integer.valueOf(counterRess.getMessage()));
            if (counterRess != null ){
                String realStock = RedisStringCache.queryCache(String.valueOf(code), CacheType.AFFORDCOUR);
                Map<String,Object> resMap  = Maps.newHashMap();
                resMap.put("realStock",counterRess.getData());
                resMap.put("balance",balance);
                StockCache.setStocks(String.valueOf(code),Integer.valueOf(realStock));
                return new CounterRes(ConstCommon.SUCCESS,"添加成功:"+orderCmd,resMap);
            }
        }else{
            return new CounterRes(ConstCommon.FALA,counterRes.getMessage(),null);
        }
        return null;
    }
}
